# -*- coding: utf-8 -*-
from datetime import timedelta
from time import time
from utils.operators.rich_sql_sensor import RichSqlSensor
# from spmi.dm.spmi.dm_finance_demand_excel import spmi_dm__dm_finance_demand_excel
from airflow.exceptions import AirflowSkipException

import pendulum

# 量本利 RichSql 非8号 15号 跳过运行
cst = pendulum.timezone('Asia/Shanghai')

class FinanceDemandRichSqlSensor(RichSqlSensor):

    def pre_execute(self, context):
        day = cst.convert(context['ti'].execution_date) + timedelta(days=1)

        schedule_date = ['18']

        if day.strftime('%d') not in schedule_date:
            print(f'{day.strftime("%d")} not in {schedule_date}, should skip')
            raise AirflowSkipException()
        else:
            print(f'{day.strftime("%d")} in {schedule_date}, run now')
            super().pre_execute(context)

label = f"doris_spmi_dm__dm_finance_demand_excel{int(time())}"
timeout = timedelta(minutes=30).seconds

doris_spmi_dm__dm_finance_demand_excel = FinanceDemandRichSqlSensor(
    task_id='doris_spmi_dm__dm_finance_demand_excel',
    pool='broker_load_pool',
    email=['yushuo@jtexpress.com','yl_bigdata@yl-scm.com'],
    conn_id='new_doris',
    pre_sql=f"""
    TRUNCATE TABLE spmi_dm.dm_finance_demand_excel PARTITION (p{{{{ execution_date | add_month(-1) | cst_month_nodash }}}});
    LOAD LABEL spmi_dm.{label} (
        DATA INFILE(
                    "hdfs://{{{{ var.value.hadoop_namespace }}}}/dw/hive/spmi_dm.db/external/dm_finance_demand_excel/mt={{{{ execution_date | add_month(-1) | cst_month_dash }}}}/*"
                    )
        INTO TABLE dm_finance_demand_excel  
    FORMAT AS 'PARQUET'
    )
    WITH BROKER '{{{{ var.json.doris_brokers | random_choice }}}}'
    PROPERTIES ('timeout'='{timeout}', 'max_filter_ratio'='0.0')""",
    poke_sql=f"SHOW LOAD FROM spmi_dm WHERE label = '{label}' ORDER BY CreateTime DESC LIMIT 1",
    sql_on_kill=f"CANCEL LOAD FROM spmi_dm WHERE LABEL = '{label}'",
    success=lambda r: r[2] == 'FINISHED',
    failure=lambda r: (r[2] is not None and r[2] == 'CANCELLED', str(r[7])),
    poke_interval=60,
    execution_timeout=timedelta(seconds=timeout + 120), )

# doris_spmi_dm__dm_finance_demand_excel << spmi_dm__dm_finance_demand_excel

